<template>
  <div class="p-2">
    <!--查询区域-->
    <div class="jeecg-basic-table-form-container">
      <a-form ref="formRef" @keyup.enter.native="searchQuery" :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24" />
      </a-form>
    </div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <!--        <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>-->
        <a-button type="primary" style="margin-bottom: 10px" @click="showModal">新增</a-button>
        <a-button type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
        <!--        <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>-->
        <!--        <a-button type="primary" @click="handleDownload" preIcon="ant-design:download-outlined">上传文件模板下载</a-button>-->
        <a-range-picker v-model:value="dateRange" style="width: 250px" />
        <a-button type="primary" @click="cx1">查询</a-button>
        <a-input v-model="Saleser" placeholder="请输入买方" style="width: 120px" @change="handleInputChange" />
        <a-button type="primary" @click="cx2">查询</a-button>
        <a-input v-model="models" placeholder="请输入型号" style="width: 120px" @change="handleInputChange2" />
        <a-button type="primary" @click="cx3">查询</a-button>
        <a-button type="primary" @click="cx4">联合查询</a-button>
        <a-button type="primary" @click="reload3">刷新</a-button>
        <!--        <a-dropdown v-if="selectedRowKeys.length > 0">-->
        <!--          <template #overlay>-->
        <!--            <a-menu>-->
        <!--              <a-menu-item key="1" @click="batchHandleDelete">-->
        <!--                <Icon icon="ant-design:delete-outlined" />-->
        <!--                删除-->
        <!--              </a-menu-item>-->
        <!--            </a-menu>-->
        <!--          </template>-->
        <!--          <a-button-->
        <!--            >批量操作-->
        <!--            <Icon icon="mdi:chevron-down" />-->
        <!--          </a-button>-->
        <!--        </a-dropdown>-->
        <!-- 高级查询 -->
        <!--        <super-query :config="superQueryConfig" @search="handleSuperQuery" />-->
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <!--        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />-->
        <TableAction :actions="getTableAction(record)" />
      </template>
      <template #bodyCell="{ column, record, index, text }"> </template>
    </BasicTable>
    <a-modal v-model:open="open" title="批次新增" @ok="handleOk" width="1200px" centered>
      <!--      <a-button type="primary" @click="handleBatchAdd" preIcon="ant-design:plus-outlined">新增</a-button>-->
      <a-input v-model:value="traners" placeholder="请输入交易方" style="width: 20%; margin-left: 2%" allow-clear @input="handleInput" />
      <div class="scroll-container" v-show="isshow" style="width: 20%; margin-left: 2%">
        <div
          v-for="(item, index) in filteredTranerData"
          :key="index"
          @click="getOptionInfo(item)"
          style="border: 1px solid #ccc; ine-height: 30px; cursor: pointer"
          >{{ item }}</div
        >
      </div>
      <!--      <div-->
      <!--        v-for="(item, index) in filteredTranerData"-->
      <!--        :key="index"-->
      <!--        @click="getOptionInfo(item)"-->
      <!--        v-show="isshow"-->
      <!--        style="border: 1px solid #ccc; ine-height: 30px; cursor: pointer; border-radius: 10rpx; width: 20%; margin-left: 2%"-->
      <!--        >{{ item }}</div-->
      <!--      >-->
      <a-table :columns="columns2" :data-source="dataSource" bordered>
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.dataIndex === 'model'">
            <div>
              <a-input v-if="editableData[record.key]" v-model:value="editableData[record.key][column.dataIndex]" @input="handleInput2(record.key)" />
              <!--                :value="models[record.key]"-->
              <div class="scroll-container" v-show="isshow2[record.key]">
                <div
                  v-for="(item, index) in filteredTranerData2"
                  :key="index"
                  @click="getOptionInfo2(item, record.key)"
                  style="border: 1px solid #ccc; line-height: 30px; cursor: pointer"
                >
                  型号：{{ item.型号 }}&nbsp;&nbsp;&nbsp;库存数量：{{ item.库存数量 }}
                </div>
              </div>
              <!--              <div-->
              <!--                v-for="(item, index) in filteredTranerData2"-->
              <!--                :key="index"-->
              <!--                @click="getOptionInfo2(item, record.key)"-->
              <!--                v-show="isshow2[record.key]"-->
              <!--                style="border: 1px solid #ccc; ine-height: 30px; cursor: pointer; border-radius: 10rpx; width: 100%"-->
              <!--                >型号：{{ item.型号 }}</div-->
              <!--              >-->
            </div>
          </template>
          <template v-if="column.dataIndex === 'unitPrice'">
            <div>
              <a-input
                v-if="editableData[record.key]"
                v-model:value="editableData[record.key][column.dataIndex]"
                @input="handleInput3(record.key)"
                @click="handleInput3(record.key)"
              />
              <!--                :value="models[record.key]"-->
              <div
                v-for="(item, index) in filteredTranerData3"
                :key="index"
                @click="getOptionInfo3(item, record.key)"
                v-show="isshow3[record.key]"
                style="border: 1px solid #ccc; ine-height: 30px; cursor: pointer; border-radius: 10rpx; width: 100%"
                >时间：{{ item.time }}<span style="margin-left: 20px">数量：{{ item.数量 }}</span
                ><span style="margin-left: 20px">单价：{{ item.单价 }}</span></div
              >
            </div>
          </template>
          <template v-if="obj.includes(column.dataIndex) && column.dataIndex !== 'unitPrice'">
            <div>
              <a-input
                v-if="editableData[record.key]"
                v-model:value="editableData[record.key][column.dataIndex]"
                @input="amount1(record.key)"
                @blur="jisuan(record.key)"
              />
              <template v-else>
                {{ text }}
              </template>
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'operation'">
            <div class="editable-row-operations">
              <span v-if="editableData[record.key]">
                <!--                <a-typography-link @click="save(record.key)"><a>保存</a></a-typography-link>-->
                <a-popconfirm title="确认操作?" @confirm="cancel(record.key)">
                  <a>&nbsp;&nbsp;删除</a>
                </a-popconfirm>
                <a @click="handleBatchAdd2()">&nbsp;&nbsp;新增</a>
              </span>
              <span v-else>
                <a @click="edit(record.key)">编辑</a>
                <a @click="handleBatchAdd2()">&nbsp;&nbsp;新增</a>
              </span>
            </div>
          </template>
        </template>
      </a-table>
      <!-- 新增合计显示 -->
      <div style="margin-top: 10px; font-weight: bold">
        合计金额: {{ alltotal }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <!--        优惠金额：<a-input-->
        <!--          type="text"-->
        <!--          v-model:value="total2"-->
        <!--          placeholder="请输入优惠金额"-->
        <!--          style="width: 12%"-->
        <!--          @input="amount2()"-->
        <!--        />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;应付额：{{ total3 }}&nbsp;&nbsp;&nbsp;&nbsp;是否支付：<a-select-->
        <!--          v-model:value="Ispay"-->
        <!--          style="width: 10%"-->
        <!--        >-->
        <!--          <a-select-option value="是">是</a-select-option>-->
        <!--          <a-select-option value="否">否</a-select-option> </a-select-->
        <!--        ><span v-if="Ispay == '是'">&nbsp;&nbsp;&nbsp;&nbsp;支付方式：</span>-->
        <!--        <a-select v-model:value="Ispay2" style="width: 10%" v-if="Ispay == '是'">-->
        <!--          <a-select-option value="微信">微信</a-select-option>-->
        <!--          <a-select-option value="支付宝">支付宝</a-select-option>-->
        <!--          <a-select-option value="银行承兑">银行承兑</a-select-option>-->
        <!--          <a-select-option value="公户收款">公户收款</a-select-option>-->
        <!--          <a-select-option value="现金">现金</a-select-option>-->
        <!--        </a-select>-->
        <span>&nbsp;&nbsp;&nbsp;&nbsp;录入人：{{ username }}-pc</span></div
      >
    </a-modal>
    <a-modal v-model:open="open2" title="批次详情" @ok="handleOk2" width="1200px" centered>
      <a-table :columns="columns3" :data-source="dataSource2" bordered>
        <template #bodyCell="{ column, text, record }">
          <template v-if="obj2.includes(column.dataIndex)">
            <div>
              <a-input v-if="editableData2[record.key]" v-model:value="editableData2[record.key][column.dataIndex]" />
              <template v-else>
                {{ text }}
              </template>
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'operation'">
            <div class="editable-row-operations">
              <!-- 根据需要添加操作按钮 -->
              <span v-if="editableData2[record.key]">
                <a-typography-link @click="save2(record.key)"><a>保存</a></a-typography-link>
                <a-popconfirm @click="cancel2(record.key)">
                  <a>&nbsp&nbsp取消</a>
                </a-popconfirm>
              </span>
              <span v-else>
                <!--                <a @click="edit2(record.key)">编辑</a>-->
                <!--                <a-popconfirm title="确认操作?" @confirm="delete2(record.key)">-->
                <!--                  <a>&nbsp&nbsp删除</a>-->
                <!--                </a-popconfirm>-->
              </span>
            </div>
          </template>
        </template>
      </a-table>
      <!-- 新增合计显示 -->
      <div style="margin-top: 10px; font-weight: bold">
        <span>&nbsp;&nbsp;&nbsp;&nbsp;录入人：{{ people }}</span></div
      >
    </a-modal>
    <!-- 表单区域 -->
    <JxcCostingModal ref="registerModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" name="ddyht-ddygSale" setup>
  import { ref, reactive, onMounted, computed, UnwrapRef, watch } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { columns, superQuerySchema } from './JxcCosting.data';
  import { list, deleteOne, batchDelete, getImportUrl, getExportUrl } from './JxcCosting.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import JxcCostingModal from './components/JxcCostingModal.vue';
  // import { useUserStore } from '/@/store/modules/user';
  // import { ref, reactive, onMounted, computed, UnwrapRef } from 'vue';
  // import { BasicTable, useTable, TableAction } from '/@/components/Table';
  // import { useListPage } from '/@/hooks/system/useListPage';
  // import { columns, superQuerySchema } from './JxcSale.data';
  // import { list, deleteOne, batchDelete, getImportUrl, getExportUrl } from './JxcSale.api';
  // import { downloadFile } from '/@/utils/common/renderUtils';
  // import JxcSaleModal from './components/JxcSaleModal.vue';
  import { useUserStore } from '/@/store/modules/user';
  import { message } from 'ant-design-vue';
  import { defHttp } from '@/utils/http/axios';
  import { cloneDeep } from 'lodash-es';
  import { pinyin } from 'pinyin-pro';
  import { Decimal } from 'decimal.js';
  const dateRange = ref([]);
  let Saleser = '';
  const models = ref();
  function handleInputChange(event) {
    const value = event.target.value;
    // 在这里处理输入框内容变化的逻辑
    console.log('输入框内容变化:', value);
    Saleser = value;
  }
  function handleInputChange2(event) {
    const value = event.target.value;
    // 在这里处理输入框内容变化的逻辑
    console.log('输入框内容变化:', value);
    models.value = value;
    console.log('models变化:', models);
  }
  const formatDate = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}/${month}/${day}`;
  };
  function cx1() {
    //TODO 这里赋值参数
    console.log('dateRange.value', dateRange.value);
    let beginTime = '';
    if (dateRange.value) {
      beginTime = formatDate(new Date(dateRange.value[0]));
    } else {
      beginTime = '';
    }
    let endTime = '';
    if (dateRange.value) {
      endTime = formatDate(new Date(dateRange.value[1]));
    } else {
      endTime = '';
    }
    Object.assign(queryParam, {
      type1: 'only',
      type2: 'time',
      type3: '',
      // beginTime: dateRange.value[0],
      // endTime: dateRange.value[1],
      beginTime: beginTime,
      endTime: endTime,
    });
    reload();
  }
  function cx2() {
    //TODO 这里赋值参数
    Object.assign(queryParam, {
      type1: 'only',
      type2: 'traner',
      type3: Saleser,
      beginTime: '',
      endTime: '',
    });
    reload();
  }
  function cx3() {
    //TODO 这里赋值参数
    Object.assign(queryParam, {
      type1: 'only',
      type2: 'model',
      type3: models.value,
      beginTime: '',
      endTime: '',
    });
    reload();
  }
  function cx4() {
    let beginTime = '';
    if (dateRange.value[0]) {
      beginTime = formatDate(new Date(dateRange.value[0]));
    }
    let endTime = '';
    if (dateRange.value[1]) {
      endTime = formatDate(new Date(dateRange.value[1]));
    }
    Object.assign(queryParam, {
      type1: 'all',
      type2: models,
      type3: Saleser,
      beginTime: beginTime,
      endTime: endTime,
      // beginTime: dateRange.value[0],
      // endTime: dateRange.value[1],
    });
    reload();
  }
  function reload3() {
    if (dateRange.value) {
      delete dateRange.value[0];
      delete dateRange.value[1];
    }
    Object.assign(queryParam, { type1: '', type2: '', type3: '', beginTime: '', endTime: '' });
    reload();
  }
  const people = ref('否');
  const Ispay = ref('否');
  const Ispay2 = ref();
  const alltotal = ref();
  const numberValue = ref([]);
  const unitPriceValue = ref([]);
  const total = ref([]);
  const total2 = ref(0);
  const total3 = ref();
  const url = ref('');
  const passw = ref('');
  const handleDownload = () => {
    alert('下载密码:   ' + passw.value + '   ,点击确定后跳转下载');
    window.open(url.value, '_blank');
  };
  const traners = ref('');
  const isshow = ref<boolean>(false); //弹窗
  const isshow2 = ref<boolean[]>([]); //弹窗
  const isshow3 = ref<boolean[]>([]); //弹窗
  const open = ref<boolean>(false); //弹窗
  const open2 = ref<boolean>(false); //弹窗
  const batchDetails = ref([]);
  const showModal = () => {
    open.value = true;
    if (dataSource.value.length > 0) {
    } else {
      const newData = {
        key: `${count.value}`,
        traner: '',
        model: '',
        number: '',
        unitPrice: '',
        remark: '',
        // disabledtype: true,
      };
      dataSource.value.push(newData);
      editableData[0] = cloneDeep(dataSource.value[0]);
    }
  };
  function shuaxin() {
    //TODO 这里赋值参数
    Object.assign(queryParam, {
      type1: 'only',
      type2: 'traner',
      type3: '',
      beginTime: '',
      endTime: '',
    });
    reload();
  }
  // 清除批量新增窗口数据的通用函数
  const clearBatchAddData = () => {
    dataSource.value = [];
    traners.value = '';
    alltotal.value = 0;
    total2.value = 0;
    total3.value = 0;
    isshow.value = false;
    for (let i = 0; i < isshow2.value.length; i++) {
      isshow2.value[i] = false;
    }
    // 清除所有编辑状态
    Object.keys(editableData).forEach(key => {
      delete editableData[key];
    });
  };

  // 监听窗口开关状态，关闭时自动清除数据
  watch(open, (newVal, oldVal) => {
    if (oldVal === true && newVal === false) {
      // 窗口从打开状态变为关闭状态时，清除数据
      clearBatchAddData();
    }
  });

  // 弹窗确认按钮
  const handleOk = (e: MouseEvent) => {
    isshow.value = false;
    for (let isshow2Key in isshow2) {
      isshow2.value[isshow2Key] = false;
    }
    if (!traners.value || traners.value == '') {
      message.error('交易方不能为空');
      return false;
    }
    console.log(e);
    console.log('确认', dataSource.value);
    
    // 修复：使用数组索引而不是key来匹配数据
    for (let i = 0; i < dataSource.value.length; i++) {
      const currentItem = dataSource.value[i];
      if (editableData[currentItem.key]) {
        Object.assign(currentItem, editableData[currentItem.key]);
        delete editableData[currentItem.key];
      }
    }
    
    let pc = dataSource.value;
    for (let i = 0; i < pc.length; i++) {
      if (pc[i].model == '') {
        message.error('型号不能为空');
        return false;
      }
      if (pc[i].number == '') {
        message.error('数量不能为空');
        return false;
      }
      if (pc[i].unitPrice == '') {
        message.error('单价不能为空');
        return false;
      }
    }
    pclr(dataSource.value);
    // message.success('保存成功');
    open.value = false; // 关闭窗口，会触发watch自动清除数据
    allsearch();
    setTimeout(function () {
      shuaxin();
    }, 500);
    // for (let i = 0; i < dataSource.value.length; i++) {
    //   delete dataSource.value[i];
    // }
    // delete dataSource.value;
    // 提示框成功
  };
  function pclr(pc) {
    console.log('批次录入');
    console.log(pc);
    // 检查 zcRental 是否为数组
    if (!Array.isArray(pc)) {
      console.error('zcRental is not an array:', pc);
      return; // 或者进行其他适当的处理
    }
    // 删除 zcRental 列表中每个对象的 key 字段
    const updatedpc = pc.map((item) => {
      if (item && typeof item === 'object') {
        delete item.key;
      }
      return item;
    });

    console.log('删除 key 字段后的 pc');
    console.log(updatedpc);
    if (!Array.isArray(updatedpc)) {
      console.error('updatedZcRental is not an array:', updatedpc);
      return; // 或者进行其他适当的处理
    }
    for (let i = 0; i < updatedpc.length; i++) {
      delete updatedpc[i].amount;
      updatedpc[i].traner = traners;
      updatedpc[i].companyId = username;
      updatedpc[i].orstate = '成本核算';
      updatedpc[i].people = username + '-pc';
    }
    //自定义一个axios请求
    defHttp.post({ url: '/ddyht/jxcCostingpici/add', data: updatedpc }).then((res) => {
      console.log('res', res);
    });
    setTimeout(function () {
      shuaxin();
    }, 500);
  }
  const count = computed(() => dataSource.value.length);
  const handleBatchAdd = () => {
    const newData = {
      key: `${count.value}`,
      traner: '',
      model: '',
      number: '',
      unitPrice: '',
      remark: '',
      // disabledtype: true,
    };
    dataSource.value.push(newData);
  };
  const handleBatchAdd2 = () => {
    unitPriceData.value = [];
    const key = count.value;
    const newData = {
      key: `${count.value}`,
      traner: '',
      model: '',
      number: '',
      unitPrice: '',
      remark: '',
    };
    dataSource.value.push(newData);
    // 修复：使用key而不是数组索引来设置editableData
    editableData[key] = cloneDeep(newData);
    for (let i = 0; i < isshow2.value.length; i++) {
      isshow2.value[i] = false;
    }
    isshow.value = false;
  };
  const edit = (key: string) => {
    editableData[key] = cloneDeep(dataSource.value.filter((item) => key === item.key)[0]);
  };
  const save = (key: string) => {
    Object.assign(dataSource.value.filter((item) => key === item.key)[0], editableData[key]);
    delete editableData[key];
    console.log('保存', dataSource.value);
  };
  const cancel = (key: string) => {
    console.log('delete', key);
    // 修复：使用splice方法正确删除数组元素
    const index = dataSource.value.findIndex((item) => item.key === key);
    if (index !== -1) {
      dataSource.value.splice(index, 1);
      // 删除对应的editableData
      delete editableData[key];
    }
  };
  // 批量新增
  const columns2 = [
    // {
    //   title: '交易方',
    //   dataIndex: 'traner',
    //   width: 'auto',
    // },
    {
      title: '型号',
      dataIndex: 'model',
      width: 'auto',
    },
    {
      title: '数量',
      dataIndex: 'number',
      width: 'auto',
    },
    {
      title: '单价',
      dataIndex: 'unitPrice',
      width: 'auto',
    },
    {
      title: '金额',
      dataIndex: 'amount',
      width: 'auto',
    },
    // {
    //   title: '备注',
    //   dataIndex: 'remark',
    //   width: 'auto',
    // },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 'auto',
    },
  ];
  const columns3 = [
    {
      title: '型号',
      dataIndex: 'model',
      width: 'auto',
    },
    {
      title: '数量',
      dataIndex: 'number',
      width: 'auto',
    },
    {
      title: '单价',
      dataIndex: 'unitPrice',
      width: 'auto',
    },
    {
      title: '金额',
      dataIndex: 'amount',
      width: 'auto',
    },
    {
      title: '交易方',
      dataIndex: 'traner',
      width: 'auto',
    },
    // {
    //   title: '操作',
    //   dataIndex: 'operation',
    //   width: 'auto',
    // },
  ];
  let obj = ['traner', 'number', 'unitPrice', 'amount'];
  let obj2 = ['model', 'number', 'unitPrice', 'amount', 'traner'];
  interface DataItem {
    key: string;
    onlyid: string;
    traner: string;
    model: string;
    // realDate: Date;
    number: number;
    unitPrice: number;
    amount: number;
    // remark: string;
  }
  interface DataItem2 {
    key: string;
    traner: string;
    model: string;
    // realDate: Date;
    number: number;
    amount: number;
    unitPrice: number;
    // remark: string;
  }
  const data: DataItem[] = [];
  const data2: DataItem2[] = [];

  const dataSource = ref(data);
  const dataSource2 = ref(data2);
  const editableData: UnwrapRef<Record<string, DataItem>> = reactive({});
  const editableData2: UnwrapRef<Record<string, DataItem2>> = reactive({});

  const showModal2 = (record: Recordable) => {
    console.log(record);
    open2.value = true;
    fetchBatchDetails(record);
  };
  const deleteModal = (record: Recordable) => {
    console.log(record);
    deleteDetails(record);
  };

  const fetchBatchDetails = async (record) => {
    try {
      const params = {
        companyId: record.companyId,
        id: record.id,
        orstate: '成本核算',
      };
      const response = await defHttp.post({ url: '/ddyht/jxcCostingpici/getBatchDetails', params });
      for (let i = 0; i < response.length; i++) {
        response[i].key = i;
      }
      console.log('response', response);
      console.log('data2', data2);
      batchDetails.value = response;
      dataSource2.value = response;
      people.value = response[0].people;
    } catch (error) {
      console.error('Failed to fetch batch details:', error);
    }
  };
  const deleteDetails = async (record) => {
    try {
      const params = {
        companyId: record.companyId,
        id: record.id,
        orstate: '成本核算',
      };
      const response = await defHttp.post({ url: '/ddyht/jxcCostingpici/deleteDetails', params });
      console.log(response);
      setTimeout(function () {
        shuaxin();
      }, 500);
    } catch (error) {
      console.error('Failed to fetch batch details:', error);
    }
  };
  // 弹窗确认按钮
  const handleOk2 = (e: MouseEvent) => {
    console.log(e);
    message.success('保存成功');
    open2.value = false;
  };
  const edit2 = (key: string) => {
    console.log('edit2', key);
    console.log('dataSource2', dataSource2);
    editableData2[key] = cloneDeep(dataSource2.value.filter((item) => key === item.key)[0]);
  };

  const save2 = (key: string) => {
    console.log('save2', key);
    console.log('dataSource2', dataSource2.value[key]);
    const index = dataSource2.value.findIndex((item) => item.key === key);
    if (index !== -1) {
      Object.assign(dataSource2.value[index], editableData2[key]);
    }
    delete editableData2[key];
    defHttp.post({ url: '/ddyht/jxcCostingpici/edit', data: dataSource2.value[key] }).then((res) => {
      console.log('res', res);
    });
    message.success('保存成功');
    setTimeout(function () {
      shuaxin();
    }, 500);
  };

  const cancel2 = (key: string) => {
    delete editableData2[key];
    message.success('取消编辑');
  };

  const delete2 = (key: string) => {
    defHttp.delete({ url: '/ddyht/jxcCostingpici/delete?id=' + dataSource2.value[key].onlyid }).then((res) => {
      console.log('res', res);
    });
    const index = dataSource2.value.findIndex((item) => item.key === key);
    if (index !== -1) {
      dataSource2.value.splice(index, 1);
    }
    message.success('删除成功');
    setTimeout(function () {
      shuaxin();
    }, 500);
  };
  function reload2() {
    Object.assign(queryParam, { type1: '' });
    reload();
  }
  const getOptionInfo = (item) => {
    console.log('item', item);
    traners.value = item;
    isshow.value = false;
  };
  const getOptionInfo2 = (item, k) => {
    console.log('item', item);
    // models[k] = item;
    editableData[k]['model'] = item.型号;
    editableData[k]['onlyid'] = item.onlyid;
    isshow2.value[k] = false;
    unitPriceData.value = [];
    defHttp.post({ url: '/ddyht/jxcCostingpici/unitPriceall', params: { companyId: username, model: item.型号 } }).then((res) => {
      console.log('unitPriceData', res);
      for (let i = 0; i < res.length; i++) {
        // modelData.value[i] = res[i].model;
        unitPriceData.value[i] = res[i];
      }
    });
  };
  const getOptionInfo3 = (item, k) => {
    console.log('item', item);
    console.log('item.单价', item.单价);
    // models[k] = item;
    editableData[k]['unitPrice'] = item.单价;
    console.log('item.onlyid', item.onlyid);
    editableData[k]['onlyid'] = item.onlyid;
    isshow3.value[k] = false;
  };
  const handleInput = () => {
    isshow.value = true;
    const inputValue = traners.value;
    if (inputValue) {
      // filteredTranerData.value = tranerData.value.filter((item) => item.includes(inputValue));
      // 将输入值转换为拼音数组
      const pinyinInput = pinyin(inputValue, { toneType: 'none', type: 'array' }).flat().join('').toLowerCase();
      filteredTranerData.value = tranerData.value.filter((item) => {
        // 将每个选项转换为拼音数组
        const pinyinItem = pinyin(item, { toneType: 'none', type: 'array' }).flat().join('').toLowerCase();
        // 检查拼音是否包含输入值
        return pinyinItem.includes(pinyinInput);
      });
    } else {
      // 如果输入框为空，展示全部数据
      filteredTranerData.value = tranerData.value;
    }
  };
  const handleInput2 = (k) => {
    isshow.value = false;
    isshow2.value[k] = true;
    // const inputValue = models[k];
    const inputValue = editableData[k]['model'];
    if (inputValue) {
      // filteredTranerData2.value = modelData.value.filter((item) => item.型号.includes(inputValue));
      // 将输入值转换为拼音数组
      const pinyinInput = pinyin(inputValue, { toneType: 'none', type: 'array' }).flat().join('');
      filteredTranerData2.value = modelData.value.filter((item) => {
        // 将每个选项转换为拼音数组
        const pinyinItem = pinyin(item.型号, { toneType: 'none', type: 'array' }).flat().join('');
        // 检查拼音是否包含输入值
        return pinyinItem.includes(pinyinInput);
      });
    } else {
      // 如果输入框为空，展示全部数据
      filteredTranerData2.value = modelData.value;
    }
  };
  const handleInput3 = (k) => {
    isshow.value = false;
    isshow3.value[k] = true;
    // const inputValue = models[k];
    const inputValue = editableData[k]['unitPrice'];
    if (inputValue) {
      filteredTranerData3.value = unitPriceData.value.filter((item) => item.单价.includes(inputValue));
    } else {
      // 如果输入框为空，展示全部数据
      filteredTranerData3.value = unitPriceData.value;
    }
    amount1(k);
  };
  const amount1 = (k) => {
    const number = new Decimal(editableData[k]['number'] || 0);
    const unitPrice = new Decimal(editableData[k]['unitPrice'] || 0);
    const amount = number.mul(unitPrice); // 高精度乘法

    numberValue[k] = number;
    unitPriceValue[k] = unitPrice;
    total[k] = amount; // 确保结果也是精确值
    let total4 = new Decimal(0);
    let j = Number(k) + 1;
    console.log('j', j);
    for (let i = 0; i < j; i++) {
      total4 = new Decimal(total4).add(new Decimal(total[i]));
    }
    alltotal.value = total4;
    // total3.value = alltotal.value - total2.value;
    total3.value = new Decimal(alltotal.value).sub(new Decimal(total2.value));
  };
  const amount2 = () => {
    total3.value = new Decimal(alltotal.value).sub(new Decimal(total2.value));
  };
  const jisuan = (k) => {
    const number = new Decimal(editableData[k]['number'] || 0);
    const unitPrice = new Decimal(editableData[k]['unitPrice'] || 0);
    const amount = new Decimal(editableData[k]['amount'] || 0);

    if (number.gt(0) && unitPrice.gt(0) && amount.eq(0)) {
      editableData[k]['amount'] = number.mul(unitPrice).toNumber(); // 数量 * 单价
    }

    if (number.eq(0) && unitPrice.gt(0) && amount.gt(0)) {
      editableData[k]['number'] = amount.div(unitPrice).toNumber(); // 金额 / 单价
    }

    if (unitPrice.eq(0) && number.gt(0) && amount.gt(0)) {
      editableData[k]['unitPrice'] = amount.div(number).toNumber(); // 金额 / 数量
    }
    amount1(k);
  };
  const modelData = ref([]);
  const unitPriceData = ref([]);
  const tranerData = ref([]);
  const filteredTranerData = ref([]);
  const filteredTranerData2 = ref([]);
  const filteredTranerData3 = ref([]);
  const formRef = ref();
  const queryParam = reactive<any>({});
  const toggleSearchStatus = ref<boolean>(false);
  const registerModal = ref();
  const userStore = useUserStore();
  const username = userStore.getUserInfo.username;
  onMounted(() => {
    const userInfo = userStore.getUserInfo;
    console.log('userInfo.username', userInfo.username);
    // defHttp.get({ url: '/ddyht/jxcInventory/xz', params: { id: '1' } }).then((res) => {
    //   console.log('res', res);
    //   if (res != '' || res != null) {
    //     let parts = res.split('*');
    //     url.value = parts[0];
    //     passw.value = parts[1];
    //   }
    // });
    allsearch();
  });
  function allsearch() {
    defHttp.post({ url: '/jxcPici/modelall2', params: { companyId: username } }).then((res) => {
      console.log('modelall', res);
      for (let i = 0; i < res.length; i++) {
        // modelData.value[i] = res[i].model;
        if(res[i].库存数量 != '0'){
          modelData.value[i] = res[i];
        }
      }
    });
    defHttp.post({ url: '/jxcPici/tranerall', params: { companyId: username } }).then((res) => {
      console.log('tranerall', res);
      for (let i = 0; i < res.length; i++) {
        tranerData.value[i] = res[i].traner;
      }
    });
  }
  //注册table数据
  // const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
  //   tableProps: {
  //     title: '销货单',
  //     api: list,
  //     columns,
  //     canResize: false,
  //     useSearchForm: false,
  //     actionColumn: {
  //       width: 120,
  //       fixed: 'right',
  //     },
  //     beforeFetch: (params) => {
  //       params.username = username;
  //       return Object.assign(params, queryParam);
  //     },
  //   },
  //   exportConfig: {
  //     name: '销货单',
  //     url: getExportUrl,
  //     params: {
  //       queryParam,
  //       username,
  //     },
  //   },
  //   importConfig: {
  //     url: getImportUrl,
  //     success: handleSuccess,
  //   },
  // });
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '成本核算',
      api: list,
      columns,
      canResize: false,
      useSearchForm: false,
      actionColumn: {
        width: 120,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        params.username = username;
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: '成本核算',
      url: getExportUrl,
      params: {
        queryParam,
        username,
      },
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });
  const [registerTable, { reload, collapseAll, updateTableDataRecord, findTableDataRecord, getDataSource }, { rowSelection, selectedRowKeys }] =
    tableContext;
  const labelCol = reactive({
    xs: 24,
    sm: 4,
    xl: 6,
    xxl: 4,
  });
  const wrapperCol = reactive({
    xs: 24,
    sm: 20,
  });

  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    searchQuery();
  }

  /**
   * 新增事件
   */
  function handleAdd() {
    registerModal.value.disableSubmit = false;
    registerModal.value.add();
  }

  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    registerModal.value.disableSubmit = false;
    registerModal.value.edit(record);
  }

  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    registerModal.value.disableSubmit = true;
    registerModal.value.edit(record);
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }

  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }

  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }

  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '详情',
        // onClick: handleEdit.bind(null, record),
        onClick: showModal2.bind(null, record),
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: deleteModal.bind(null, record),
          placement: 'topLeft',
        },
        // onClick: deleteModal.bind(null, record),
      },
    ];
  }

  /**
   * 下拉操作栏
   */
  function getDropDownAction(record) {
    return [
      {
        label: '详情',
        onClick: showModal2.bind(null, record),
        // onClick: handleDetail.bind(null, record),
      },
      // {
      //   label: '删除',
      //   popConfirm: {
      //     title: '是否确认删除',
      //     confirm: handleDelete.bind(null, record),
      //     placement: 'topLeft',
      //   },
      // },
    ];
  }

  /**
   * 查询
   */
  function searchQuery() {
    reload();
  }

  /**
   * 重置
   */
  function searchReset() {
    formRef.value.resetFields();
    selectedRowKeys.value = [];
    //刷新数据
    reload();
  }
</script>

<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    padding: 0;
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 24px;
      white-space: nowrap;
    }
    .query-group-cust {
      min-width: 100px !important;
    }
    .query-group-split-cust {
      width: 30px;
      display: inline-block;
      text-align: center;
    }
    .ant-form-item:not(.ant-form-item-with-help) {
      margin-bottom: 16px;
      height: 32px;
    }
    :deep(.ant-picker),
    :deep(.ant-input-number) {
      width: 100%;
    }
  }
  .scroll-container {
    width: 100%;
    max-height: 150px;
    overflow-y: auto;
    border-radius: 5px;
    border: 1px solid #ccc;
  }
</style>
